<template>
  <PageContainer>
    <view class="container">
      <Header :title="`${editData ? '编辑' : '添加'}题目`" :is-box-shadow="false" />
      <BasicsForm @register="onRegister" @on-schema-change="onSchemaChange" />
      <view v-if="showItemContent" class="item-content mt-12 pa-16">
        <view class="title mb-16">
          <text>选项内容</text>
        </view>
        <template v-for="(item, index) in itemContent" :key="index">
          <view class="item-content__group mb-16 disFlxAC">
            <FormInput style="flex: 1" v-model="item.text"  />
            <view class="ali-icon ml-16" @click="delItemContent(index)">&#xe686;</view>
          </view>
        </template>
        <view class="item-content__add disFlxAC py-16" @click="addItemContent">
          <text class="ali-icon mr-4">&#xe8df;</text>
          <text>添加选项</text>
        </view>
      </view>
      <TButtonGroup>
        <TButton class="gutter-btn" text="保存题目" type="primary" @click.stop="handleSubmit" />
      </TButtonGroup>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* createFormItem 添加题目 */
  import Header from '@/components/Header/index.vue';
  import PageContainer from '@/components/PageContainer/index.vue';
  import BasicsForm from '@/components/Form/BasicsForm.vue';
  import { useForm, type FormSchema, type ComponentProps } from '@/components/Form';
  import type { ComponentType, Localdata, OnchangeArgument } from '@/components/Form/types';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import FormInput from '@/components/Form/components/FormInput.vue';
  import { computed, ref, unref } from 'vue';
  import { Toast } from '@/utils';
  import { navigateBack, onLoad } from '@/router';
  import type { CreateFormItem } from '@/router/types/modules';
  import { buildUUID } from '@/utils/uuid';
  import { customFormItemTypeList } from '@/api';
  import { localDataMapping } from '@/components/Form/hooks/useForm';

  const itemContent = ref<Localdata[]>([]);
  const currentType = ref<ComponentType>();
  const showItemContent = computed(() => {
    const component = currentType.value;
    const bol =
      component === 'RadioGroup' || component === 'CheckboxGroup' || component === 'Select';
    if (bol && itemContent.value.length === 0) {
      addItemContent();
    }
    return bol;
  });

  const [register, { validate, setFieldsValue, updateSchema }] = useForm({
    labelAlign: 'left',
    validateTrigger: 'bind',
    schemas: [
      {
        label: '题目信息',
        field: 'Divider',
        component: 'Divider',
      },
      {
        field: 'label',
        label: '题目标题',
        component: 'InputTextArea',
        componentProps: {
          maxlength: 1000,
          showWordLimit: true
        },
        required: true
      },
      {
        label: '填写类型',
        component: 'Select',
        field: 'component',
        required: true,
        isOnChange: true,
        componentProps: {
          localdata: [],
        },
      },
      {
        label: '填写提示',
        component: 'Input',
        field: 'placeholder',
        required: true,
        defaultValue: '请填写',
        rules: [
          {
            maxLength: 30,
            errorMessage: '最多输入30个字符',
          },
        ],
      },
      {
        label: '此题必填',
        field: 'required',
        component: 'Switch',
        defaultValue: false,
      },
    ],
  });

  async function onRegister(e: any) {
    register(e);
    if (editData.value) {
      const { label, component, componentProps, required } = editData.value;
      const props = componentProps as ComponentProps;
      currentType.value = component;
      setFieldsValue({
        label,
        component,
        required,
        placeholder: props?.placeholder || '',

      });
      if (props) {
        itemContent.value = (props?.localdata || []) as Localdata[]
      }
    }
    customFormItemTypeList().then((res) => {
      updateSchema({
        field: 'component',
        dynamicDisabled: !!editData.value?.dataType,
        componentProps: {
          localdata: localDataMapping(res, {
            label: 'name',
            value: 'type',
          }),
        },
      });
    });
  }

  let success = ref<CreateFormItem['success']>();
  const editData = ref<FormSchema>();
  onLoad<'createFormItem'>((op) => {
    editData.value = op.item;
    success.value = op.success;
  });

  function addItemContent() {
    const value = itemContent.value.length + 1;
    itemContent.value.push({
      text: `选项${value}`,
      value: buildUUID(),
    });
  }

  function delItemContent(index: number) {
    if (itemContent.value.length === 1) return Toast('至少保留一个选项');
    itemContent.value.splice(index, 1);
  }

  async function handleSubmit() {
    const values = await validate();
    const item = {
      label: values.label,
      field: editData.value?.field || buildUUID(),
      required: values.required,
      component: values.component,
      dataType: editData.value?.dataType,
      componentProps: {
        placeholder: values.placeholder,
        localdata: [] as Localdata[],
      },
    };
    if (showItemContent.value) {
      item.componentProps.localdata = [...unref(itemContent)];
    }
    success.value?.(item);
    navigateBack();
  }

  const onSchemaChange = (e: OnchangeArgument) => {
    if (e.field === 'component') {
      currentType.value = e.val;
    }
  };
</script>

<style lang="scss" scoped>
  .item-content {
    background-color: #fff;
    padding-bottom: 0;
    .title {
      color: #999996;
      font-size: 28rpx;
    }
    &__group {
      .ali-icon {
        font-size: 48rpx;
        color: #999996;
        flex-shrink: 0;
      }
    }
    &__add {
      justify-content: center;
      color: #2878ff;
      font-size: 28rpx;
      border-top: 1px solid #ebedf0;
      .ali-icon {
        font-size: 48rpx;
      }
    }
  }
</style>
